#include "stdDataBase.h"
#include "stdSqliteDataBase.h"
#include <sqlite3.h>
#include <iostream>
using namespace std;
bool stdSqliteDataBase::connectDB(const char *loccalname)
{
    int ret = sqlite3_open(loccalname, &db);
    if (ret != SQLITE_OK)
    {
        cout << "error" << sqlite3_errmsg(db) << endl;
        return true;
    }
    return false;
}
QueryResult stdSqliteDataBase::query(const std::string &sql)
{
    QueryResult res;
    int row = 0;
    int colum = 0;
    char **result = nullptr;
    // 查表
    sqlite3_get_table(db, sql.c_str(), &result, &row, &colum, NULL);

    // 字段
    for (int i = 0; i < colum; i++)
    {
        res.columeName.push_back(result[i]);
    }

    // 数据
    for (int row = 0; row < row; row++)
    {
        std::vector<std::string> rowdata;
        for (int col = 0; col < colum; col++)
        {
            rowdata.push_back(result[(row + 1) * colum + col]);
        }
        res.datas.push_back(rowdata);
    }
    return res;
}

bool stdSqliteDataBase::execute(const std::string &sql)
{
    int ret = sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL);
    if (ret != SQLITE_OK)
    {
        std::cout << "error" << sqlite3_errmsg(db) << std::endl;
        return false;
    }
    return true;
}

void stdSqliteDataBase::close()
{
    sqlite3_close(db);
}
